<template>
  <div>
    <form action="/">
      <van-search
        background="#3296fa"
        v-model.trim="value"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="$router.back()"
        @focus="isShowRes=false"
      />
    </form>

    <!-- 引入组件 -->
    <search-results :searchText="value" v-if="isShowRes"></search-results>
    <search-history @clear="history=[]" @onSearch="onSearch" :history="history" v-else-if="!value"></search-history>
    <search-suggestion @onSearch="onSearch" v-else :searchText="value"></search-suggestion>

  </div>
</template>

<script>
import { Toast } from 'vant'
import SearchHistory from './components/SearchHistory.vue'
import SearchResults from './components/SearchResults.vue'
import { getStorage, setStorage } from '@/utils/storage.js'
import SearchSuggestion from './components/SearchSuggestion.vue'
export default {
  components: { SearchHistory, SearchResults, SearchSuggestion },
  name: 'Search',
  data () {
    return {
      value: '',
      isShowRes: false,
      history: getStorage('TT-HISTORY') || []
    }
  },

  created () {

  },
  watch: {
  // 监听history，发生变化，存储到本地
    history: {
      deep: true,
      handler (newVal) {
        setStorage('TT-HISTORY', newVal)
      }
    }
  },
  methods: {
    onSearch (val) {
      this.value = val
      this.isShowRes = true
      // 存储搜索历史
      this.history.unshift(val)
      // 去重
      this.history = [...new Set(this.history)]
    },
    onCancel () {
      Toast('取消')
    }
  }
}
</script>

<style scoped lang='less'>
.van-search__action{
  color: #fff;
}
</style>
